﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;

namespace SATF.BI
{
    public class SortHelper
    {

        private static IList<T> IListOrderBy<T>(IList<T> list, string propertyName) where T : new()
        {
            if (list == null || list.Count == 0) return list;
            Type elementType = list[0].GetType();
            PropertyInfo proertyInfo = elementType.GetProperty(propertyName);
            ParameterExpression parameter = Expression.Parameter(elementType, "");
            Expression body = Expression.Property(parameter, proertyInfo);
            Expression sourceExpression = list.AsQueryable().Expression;
            Type sourcePropertyType = proertyInfo.PropertyType;
            Expression lambda = Expression.Call(
                typeof(Queryable), "OrderBy",
                new Type[] { elementType, sourcePropertyType },
                sourceExpression, Expression.Lambda(body, parameter));
            return list.AsQueryable().Provider.CreateQuery<T>(lambda).ToList<T>();
        }

        private static IList<T> IListOrderByDescending<T>(IList<T> list, string propertyName) where T : new()
        {
            if (list == null || list.Count == 0) return list;
            Type elementType = list[0].GetType();
            PropertyInfo proertyInfo = elementType.GetProperty(propertyName);
            ParameterExpression parameter = Expression.Parameter(elementType, "");
            Expression body = Expression.Property(parameter, proertyInfo);
            Expression sourceExpression = list.AsQueryable().Expression;
            Type sourcePropertyType = proertyInfo.PropertyType;
            Expression lambda = Expression.Call(
                typeof(Queryable), "OrderByDescending",
                new Type[] { elementType, sourcePropertyType },
                sourceExpression, Expression.Lambda(body, parameter));
            return list.AsQueryable().Provider.CreateQuery<T>(lambda).ToList<T>();
        }


        public static IList<T> IListOrderBy<T>(IList<T> list, string sortField, string sortDirection) where T : new()
        {
            switch (sortDirection.ToUpper())
            {
                case "ASC":
                    return IListOrderBy(list, sortField);
                default:
                    return IListOrderByDescending(list, sortField);

            }
        }
        

    }
}
